package hystrix;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class SubCommand extends HystrixCommand<String> {
    /**
     * Construct a {@link HystrixCommand} with defined {@link HystrixCommandGroupKey}.
     * <p>
     * The {@link HystrixCommandKey} will be derived from the implementing class name.
     *
     * @param group {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixCommand} objects.
     *              <p>
     *              The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interact with,
     *              common business purpose etc.
     */
    String url;
    protected SubCommand(String group,String url) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(group)).andCommandPropertiesDefaults(
                HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(1000))
        );
        this.url = url;
    }

    /**
     * Implement this method with code to be executed when {@link #execute()} or {@link #queue()} are invoked.
     *
     * @return R response type
     * @throws Exception if command execution fails
     */
    protected String run() throws Exception {
        System.out.println("本段文字是通过HelloCommand的回滚机制触发的");
        CloseableHttpResponse response = HttpClients.createDefault().execute(new HttpGet(url));
        String responseString = EntityUtils.toString(response.getEntity());

        return responseString;
    }

    @Override
    protected String getFallback() {
        String s = "Hystrix的回滚链启动,本段文字是由subCommand的回滚机制触发的";
        System.out.println(s);
        return s;

    }
}
